package com.nj9you.sdk.user;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.nj9you.sdk.params.User;
import com.nj9you.sdk.utils.AES;
import com.nj9you.sdk.utils.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by ck01- on 2017/7/4.
 */

public class UserManager {
    private volatile static UserManager sUserManager;
    private SharedPreferences mSharedPreference;

    private UserManager(Context context) {
        mSharedPreference = context.getSharedPreferences("nj9you_user", Context.MODE_PRIVATE);
    }

    public static UserManager get(Context context) {
        synchronized (UserManager.class) {
            if (sUserManager == null) {
                sUserManager = new UserManager(context);
            }
        }
        return sUserManager;
    }

    /**
     * 保存登录用户
     *
     * @param user
     */
    public void saveUser(User user) {
        if (user == null || TextUtils.isEmpty(user.getUsername())
                || TextUtils.isEmpty(user.getPassword())) {
            Log.d(Log.TAG, "User Exception");
            return;
        }
        List<User> users = loadUsers();
        if (users == null) {
            users = new ArrayList<User>();
        }
        String newUsername = user.getUsername();
        Iterator<User> iterator = users.iterator();
        while (iterator.hasNext()) {
            User u = iterator.next();
            if (u != null && newUsername.equals(u.getUsername())) {
                iterator.remove();
            }
        }
        users.add(user);
        String content = toJson(users);
        // Log.d(Log.TAG, "content : " + content);
        mSharedPreference.edit().putString("user_list", content).commit();
    }

    /**
     * 删除保存的用户
     *
     * @param user
     */
    public void removeUser(User user) {
        if (user == null || TextUtils.isEmpty(user.getUsername())) {
            Log.d(Log.TAG, "User Exception");
            return;
        }
        List<User> list = loadUsers();
        if (list != null && list.size() > 0) {
            Iterator<User> iterator = list.iterator();
            while (iterator.hasNext()) {
                User u = iterator.next();
                if (user.getUsername().equals(u.getUsername())) {
                    iterator.remove();
                }
            }
        }
        String content = toJson(list);
        // Log.d(Log.TAG, "content : " + content);
        mSharedPreference.edit().putString("user_list", content).commit();
    }

    /**
     * 设置当前登录用户
     *
     * @param user
     */
    public void setCurrentUser(User user) {
        if (user != null) {
            mSharedPreference.edit().putString("last_user", user.getUsername()).commit();
            mSharedPreference.edit().putString("last_user_id", user.getId()).commit();
        }
    }

    /**
     * 读取当前用户
     *
     * @return
     */
    public User loadCurrentUser() {
        User user = new User();
        String username = mSharedPreference.getString("last_user", null);
        String userid = mSharedPreference.getString("last_user_id", null);
        if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(userid)) {
            user.setUsername(username);
            user.setId(userid);
        }
        return user;
    }

    /**
     * 读取所有登录过的用户
     *
     * @return
     */
    public List<User> loadUsers() {
        String usercontent = mSharedPreference.getString("user_list", null);
        // Log.d(Log.TAG, "usercontent : " + usercontent);
        if (!TextUtils.isEmpty(usercontent)) {
            return toUsers(usercontent);
        }
        return null;
    }

    /**
     * 设置登录时间
     */
    public void setLoginTime() {
        mSharedPreference.edit().putLong("login_time", System.currentTimeMillis()).commit();
    }

    /**
     * 获取上次手动登录时间
     *
     * @return
     */
    public long getLoginTime() {
        return mSharedPreference.getLong("login_time", 0);
    }

    /**
     * 设置记住密码
     *
     * @param remember
     */
    public void setRememberPassword(boolean remember) {
        mSharedPreference.edit().putBoolean("remember_password", remember).commit();
    }

    /**
     * 是否记住密码
     *
     * @return
     */
    public boolean isRememberPassword() {
        return mSharedPreference.getBoolean("remember_password", false);
    }

    /**
     * 注销用户
     */
    public void logout() {
        setCurrentUser(new User());
    }

    /**
     * 字符串转对象列表
     *
     * @param content
     * @return
     */
    private List<User> toUsers(String content) {
        List<User> list = new ArrayList<User>();
        try {
            JSONArray jarray = new JSONArray(content);
            User user = null;
            JSONObject jobj = null;
            for (int i = 0; i < jarray.length(); i++) {
                user = new User();
                jobj = jarray.getJSONObject(i);
                if (jobj != null) {
                    if (jobj.has("username")) {
                        user.setUsername(jobj.getString("username"));
                    }
                    if (jobj.has("password")) {
                        user.setPassword(AES.decode(jobj.getString("password")));
                    }
                }
                list.add(user);
            }
        } catch (Exception e) {
        }
        return list;
    }

    /**
     * 对象列表转字符串
     *
     * @param list
     * @return
     */
    private String toJson(List<User> list) {
        if (list != null && list.size() > 0) {
            JSONArray jarray = new JSONArray();
            JSONObject jobj = null;
            for (User user : list) {
                try {
                    jobj = new JSONObject();
                    jobj.put("username", user.getUsername());
                    jobj.put("password", AES.encode(user.getPassword()));
                    jarray.put(jobj);
                } catch (Exception e) {
                    Log.e(Log.TAG, "error : " + e);
                }
            }
            return jarray.toString();
        }
        return null;
    }
}
